<template>
    <div class="address-selector">
        <h1>添加收货地址</h1>

        <form @submit.prevent="submitForm">

            <div class="selector-group">
                <label>省份：</label>
                <select v-model="selectedProvince" @change="ProvinceChange">
                    <option value="">请选择省份</option>
                    <option v-for="(province, code) in provinces" :key="code" :value="code">
                        {{ province.n }}
                    </option>
                </select>
            </div>

            <div class="selector-group">
                <label>城市：</label>
                <select v-model="selectedCity" @change="CityChange" :disabled="!selectedProvince">
                    <option value="">请选择城市</option>
                    <option v-for="(city, code) in cities" :key="code" :value="code">
                        {{ city.n }}
                    </option>
                </select>
            </div>

            <div class="selector-group">
                <label>区县：</label>
                <select v-model="selectedCounty" :disabled="!selectedCity">
                    <option value="">请选择区县</option>
                    <option v-for="(county, code) in counties" :key="code" :value="code">
                        {{ county.n }}
                    </option>
                </select>
            </div>

            <div class="selector-group">
                <label>详细地址：</label>
                <textarea v-model="xiangxi" placeholder="请输入详细地址，如街道、楼牌号等"></textarea>
            </div>

             <div class="selector-group">
                <label>收件人</label>
                <textarea v-model="name" placeholder="收件人"></textarea>
            </div>

            <div class="selector-group">
                <label>联系电话</label>
                <textarea v-model="phone" placeholder="联系电话" @blur="validatePhone" :class="{ 'error': errors.phone }"></textarea>
                  <span v-if="errors.phone" class="error-text">{{ errors.phone }}</span>
            </div>

            <div class="selector-group">
                <label>备注</label>
                <textarea v-model="remark" placeholder="备注"></textarea>
            </div>

            <div class="form-actions">
                <button @click="saveAddress">保存地址</button>
                <button @click="resetForm">重置</button>
            </div>

            <div class="selected-address" v-if="fullAddress">
                <h3>选中的地址：</h3>
                <p>{{ fullAddress }}</p>
            </div>
        </form>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import Area from '/public/area_format_object.json'
import axios from 'axios'

const selectedProvince = ref('')
const selectedCity = ref('')
const selectedCounty = ref('')
const xiangxi = ref('')
const remark = ref('')
const name = ref('')
const phone = ref('')
const errors = ref({})

// 省份
const provinces = computed(() => Area)

// 城市
const cities = computed(() => {
    if (selectedProvince.value && Area[selectedProvince.value]) {
        return Area[selectedProvince.value].c
    }
    return;
})

// 区县
const counties = computed(() => {
    if (selectedCity.value && cities.value[selectedCity.value]) {
        return cities.value[selectedCity.value].c
    }
    return;
})

// 完整地址
const fullAddress = computed(() => {
    let address = ''
    if (selectedProvince.value) {
        address += Area[selectedProvince.value].n
    }
    if (selectedCity.value && Area[selectedProvince.value]) {
        address += ' ' + Area[selectedProvince.value].c[selectedCity.value].n
    }
    if (selectedCounty.value && cities.value[selectedCity.value]) {
        address += ' ' + cities.value[selectedCity.value].c[selectedCounty.value].n
    }
    if (xiangxi.value) {
        address += ' ' + xiangxi.value.trim()
    }
    return address
})

const ProvinceChange = () => {
    selectedCity.value = ''
    selectedCounty.value = ''
}

const validatePhone = () => {
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phone.value) {
    errors.value.phone = '请输入手机号'
    return false
  } else if (!phoneRegex.test(phone.value)) {
    errors.value.phone = '手机号格式不正确(13-19开头的11位数字)'
    return false
  } else {
    delete errors.value.phone
    return true
  }
}
// 保存地址
const saveAddress = async () => {
    if (!selectedProvince.value) {
        alert('请选择省份')
        return
    }

    if (!selectedCity.value) {
        alert('请选择城市')
        return
    }

    if (!selectedCounty.value) {
        alert('请选择区县')
        return
    }

    if (!xiangxi.value.trim()) {
        alert('请输入详细地址')
        return
    }

    if (!name.value.trim()) {
        alert('收件人不能为空')
        return
    }

     if (!validatePhone()) {
        alert('请输入正确的手机号')
        return
    }
    const userId = window.sessionStorage.getItem('id');

    const addressData = {
        userId: userId,
        address: fullAddress.value,
        remark: remark.value,
        name: name.value,
        phone: phone.value
    }


    const response = await axios.post('/api/addUserAddress', addressData, {
        headers: {
            'Content-Type': 'application/json'
        }
    })

    if (response.data.code !== 5200) {
        alert('地址保存失败（最多存在16个地址）');
        return
    }
    alert('地址保存成功');
    window.location.href = '/addressList'
}

// 重置表单
const resetForm = () => {
    selectedProvince.value = ''
    selectedCity.value = ''
    selectedCounty.value = ''
    xiangxi.value = ''
    remark.value = ''
    name.value = ''
    phone.value = ''
}
</script>


<style scoped>
.address-selector {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
}

.address-selector h1 {
    text-align: center;
    margin-bottom: 30px;
    color: #333;
}

.form-group,
.selector-group {
    margin-bottom: 20px;
}

.form-group label,
.selector-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: bold;
}

.form-group input,
.form-group textarea,
.selector-group select,
.selector-group textarea {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    box-sizing: border-box;
}

.form-group textarea,
.selector-group textarea {
    height: 80px;
    resize: vertical;
}

.form-actions {
    display: flex;
    gap: 10px;
    justify-content: center;
    margin-top: 30px;
}


.selected-address {
    margin-top: 30px;
    padding: 15px;
    border-radius: 4px;
    border: 1px solid #b8daff;
}
</style>